/*
 * DoAnJava3View.java
 */
package doanjava3;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.WriteAbortedException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.event.ChangeEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 * The application's main frame.
 */
public class DoAnJava3View extends FrameView
{

    private static Socket clientsocket;
    private static int iport = 3200;
    private static BufferedReader bufferedreader = null;
    private static BufferedWriter bufferedwriter = null;
//    private static ObjectOutputStream objectoutputstream = null;
    private static OutputStream outputstream = null;

    public static void main(String args[])
    {
        DoAnJava3App app = new DoAnJava3App();
        app.main(args);
        try
        {
            serversocket = new ServerSocket(iport);

        } catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
        while (true)
        {
            try
            {
                SKClient1 = serversocket.accept();
                if (SKClient1 != socketclient)
                {
                    if (socketclient != null)
                    {
                        SKClient2 = socketclient;
                        socketclient.close();
                    }
                    socketclient = SKClient1;
                    new DoAnJava3View.ServerThread("");
                }

            } catch (Exception ex)
            {
//                System.out.println(ex.getMessage() + "bao anh");
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="phần khai báo class ServerThread">

    private static void readConnectInformation() throws IOException
    {
        bufferedreader = new BufferedReader(new InputStreamReader(socketclient.getInputStream()));
        bufferedwriter = new BufferedWriter(new OutputStreamWriter(socketclient.getOutputStream()));
        //server nhap ip, username, password tu client goi qua
        ip = bufferedreader.readLine();
        StrName = bufferedreader.readLine();
        pass = bufferedreader.readLine();
        System.out.println("thong tin lien ket: " + ip + "       " + StrName + "      " + pass);
    }

    private static void sendReportFailToClient() throws IOException
    {
        bufferedwriter.write("fail");
        bufferedwriter.newLine();
        bufferedwriter.flush();
        bufferedreader.close();
        bufferedwriter.close();
        socketclient.close();
    }

    private static void sendReportPassToClient() throws IOException
    {
        bufferedwriter.write("pass");
        bufferedwriter.newLine();
        bufferedwriter.flush();
        System.out.println("thong tin lien ket da duoc chap nhan");
    }

    private static JTable queryDadabase(String strsql, ArrayList<JTable> lsttbope)
    {
        clsQuery clsquery = new clsQuery(strsql, lsttbope);
        return clsquery.queryDadabase();
    }

    public static class ServerThread implements Runnable
    {

        String name;
        Thread t;

        ServerThread(String threadname)
        {
            name = threadname;
            t = new Thread(this, name);
            t.start();
        }

        @Override
        public void run()
        {
            try
            {
                try
                {
                    thucHienThread();
                } catch (AWTException ex)
                {
                    Logger.getLogger(DoAnJava3View.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex)
            {
                Logger.getLogger(DoAnJava3View.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void thucHienThread() throws AWTException, IOException
    {
        while (true)
        {
            if (socketclient.isClosed() == false)
            {
                //nhan thong tin ket noi gom ip, username, password
                readConnectInformation();
                //kiem tra xem ip, username, password co dung hay ko
                if (strIP.equals(ip) && strUserName.equals(StrName) && strPass.equals(pass))
                {
                    sendReportPassToClient();   //goi "pass" cho client
                    while (true)
                    {
                        String strSQLreceived;

                        while (!socketclient.isClosed())
                        {
                            if (!socketclient.isClosed())
                            {
                                outputstream = socketclient.getOutputStream();
                                bufferedreader = new BufferedReader(new InputStreamReader(socketclient.getInputStream()));
                                bufferedwriter = new BufferedWriter(new OutputStreamWriter(outputstream));
                                ObjectOutputStream objectoutputstream = new ObjectOutputStream(outputstream);
//                                objectoutputstream = new ObjectOutputStream(new BufferedOutputStream(outputstream));
                                //Server nhan cau truy van SQL tu Client
                                strSQLreceived = bufferedreader.readLine();
                                //neu socketclient disconnect
                                if (strSQLreceived == null)
                                {
                                    socketclient.close();
                                    return;
                                }
                                else
                                {
                                    tfSQL.setText(new clsQuery(strSQLreceived).formateSQL());
                                    System.out.println("Server Received : " + strSQLreceived);
                                    //goi ham truy van chuoi SQL de truy van CSDL, va tra ve ket qua la 1 JTable
                                    JTable table = queryDadabase(strSQLreceived, lstTBOpe);
                                    try
                                    {
                                        objectoutputstream.reset();
                                        objectoutputstream.writeObject(table);
                                        objectoutputstream.flush();
                                    } catch (Exception e)
                                    {
                                        System.out.println("da co scash xay ra!");
                                    }
                                }
                            }
                            else
                            {
                                socketclient.close();
                                return;
                            }
                        }
                        return;
                    }
                }
                else    //thong tin ket noi ko hop le
                {
                    sendReportFailToClient();   //goi "fail" qua client va dong ket noi
                    return;
                }
            }
            else
                return;
        }
    }
    // </editor-fold>
    //khai bao doi tuong clsDatabase
    private clsDatabase myDatabase;
    //ten duong dan den file can doc/ghi
    private String pathFile = "file.txt";
    //duong dan den file database
    File directory = new File("");
    private String pathData = directory.getAbsolutePath() + "\\Database.ser";
//    private String pathData = "resources/Database.ser";
    //ten duong dan den imageicon 
    private String pathImageIcon = "resources/table.png";
    //ten cua bang moi duoc tao
    String name = "";
    //list chua danh sach cac bang o che do design
    private ArrayList<JTable> lstTBDes = new ArrayList<JTable>();
    //list chua danh sach cac bang o che do open
    private static ArrayList<JTable> lstTBOpe = new ArrayList<JTable>();
    //list chua danh sach cac scrollpane cua moi tabbedpanel
    private ArrayList<JScrollPane> lstCrollP = new ArrayList<JScrollPane>();
    //list chua tinh trang cac bang co duoc luu hay khong (true/false)
    private ArrayList<Boolean> lstIsSaved = new ArrayList<Boolean>();
    //lay ve model cua mainList de lam viec voi cac item cua no
    DefaultListModel modelList = new DefaultListModel();
    DoAnJava3AboutBox doanAbout;
    //khai bao cac bien ho tro ket noi giua server va client
    static Socket socketclient;
    static ServerSocket serversocket;
    static String strReport = "";
    static String strIP = "";
    static String strUserName = "";
    static String strPass = "";
    public static String ip;
    public static String pass;
    public static String StrName;
    static boolean check = false;
    private static Socket SKClient1;
    private static Socket SKClient2;

    public DoAnJava3View(SingleFrameApplication app) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        super(app);
        initComponents();
        myDatabase = new clsDatabase();
        //load Database tu file len bien myDatabase
        myDatabase = loadDatabaseFromFile(pathData);
        lstTBDes = myDatabase.getLstTBDes();
        lstTBOpe = myDatabase.getLstTBOpe();
        //dat mau chu cho tabbedpanel
        mainTabP.setForeground(Color.red);
        //dat mau chu cho mainList
        mainList.setForeground(Color.red);
        //lang nghe su kien khi click vao dong cuoi cung cua table thi phat sinh them dong moi
        for (int i = 0; i < lstTBDes.size(); i++)
        {
            newRowListener(lstTBDes.get(i));
            newRowListener(lstTBOpe.get(i));
            //xu ly su kien thay doi du lieu o o dau tien cua dong cua bang desing(gia tri la Column Name)
            changCellDataListtener(lstTBDes.get(i));
            //cho moi table lang nghe su kien khi nhan phim KeyUp - KeyDown
            lstTBDes.get(i).addKeyListener(new KeyListener()
            {

                //bat su kien nha phim ra
                public void keyReleased(KeyEvent e)
                {
                    verifyRowPosition(lstTBDes);
                }

                public void keyTyped(KeyEvent e)
                {
                }

                public void keyPressed(KeyEvent e)
                {
                }
            });
            lstTBOpe.get(i).addKeyListener(new KeyListener()
            {

                //bat su kien nha phim ra
                public void keyReleased(KeyEvent e)
                {
                    verifyRowPosition(lstTBOpe);
                }

                public void keyTyped(KeyEvent e)
                {
                }

                public void keyPressed(KeyEvent e)
                {
                }
            });
        }

        //lay ve danh sach cac bang open tu file

        //hien thi cac bang design len tab panel va list
        viewListTable(lstTBDes);
        System.out.println("Da load du lieu tu file thanh cong!");
        //khoi tao cac dieu kien ban dau can thiet cho Server
        System.out.println("Dang khoi tao ket noi....");
        initInputServer();
        System.out.println("Khoi tao ket noi thanh cong!");
        System.out.println("-----------------------------------------------");
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++)
        {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
        {

            public void propertyChange(java.beans.PropertyChangeEvent evt)
            {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName))
                {
                    if (!busyIconTimer.isRunning())
                    {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                }
                else if ("done".equals(propertyName))
                {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                }
                else if ("message".equals(propertyName))
                {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                }
                else if ("progress".equals(propertyName))
                {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox()
    {
        if (aboutBox == null)
        {
            JFrame mainFrame = DoAnJava3App.getApplication().getMainFrame();
            aboutBox = new DoAnJava3AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DoAnJava3App.getApplication().show(aboutBox);
    }

    private JTable createTableDesign()
    {
        //tao 2 cot cho bang
        String colName[] =
        {
            "Field Name", "Data Type"
        };
        //tao 1 dong du lieu trong cho bang
        String datarow[][] =
        {
            {
                "ID", "Integer"
            },
            {
                null, null
            }
        };
        //tao bang
        DefaultTableModel defmodel = new DefaultTableModel(datarow, colName);
        JTable tbdesign = new JTable(defmodel);
        //tao combobox kieu du lieu cho o trong bang
        JComboBox com = new JComboBox();
        //them combobox kieu du lieu cua cot vao bang moi tao
        com.addItem("Integer");
        com.addItem("String");
        DefaultCellEditor cell = new DefaultCellEditor(com);
        tbdesign.getColumnModel().getColumn(1).setCellEditor(cell);
        return tbdesign;
    }

    private void exitProgrameFunction()
    {
        // TODO add your handling code here:
        //exitProgramFunction();
        //khong cho phep edit cac bang truoc khi thoat
        for (int i = 0; i < lstTBDes.size(); i++)
        {
            lstTBDes.get(i).setRowSelectionInterval(0, 0);
            lstTBDes.get(i).removeEditor();
            lstTBOpe.get(i).setRowSelectionInterval(0, 0);
            lstTBOpe.get(i).removeEditor();
        }
        //gan cac danh sach cho doi tuong clsDatabase
        myDatabase.setLstTBDes(lstTBDes);
        myDatabase.setLstTBOpe(lstTBOpe);
        saveDatabaseToFile(myDatabase, pathData);
        System.out.println(myDatabase.getLstTBOpe().size());
        //cho mainTabP chon o vi tri tab cuoi cung, de sau sau khoi dong len van nhu vay
        mainTabP.setSelectedIndex(mainTabP.getTabCount() - 1);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        mainTabP = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        mainList = new javax.swing.JList();
        mainTollBar = new javax.swing.JToolBar();
        btnAddtable = new javax.swing.JButton();
        btnDeletetable = new javax.swing.JButton();
        btnSavetable = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnDesignTable = new javax.swing.JButton();
        btnOpenTable = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        btnInsertrow = new javax.swing.JButton();
        btnDeleterow = new javax.swing.JButton();
        jSeparator5 = new javax.swing.JToolBar.Separator();
        btnGofirst = new javax.swing.JButton();
        btnGoprevious = new javax.swing.JButton();
        lbrow = new javax.swing.JLabel();
        btnGonext = new javax.swing.JButton();
        btnGolast = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnExit = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        tfSQL = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        tfPassword = new javax.swing.JTextField();
        tfUsername = new javax.swing.JTextField();
        tfIp = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        TableMenu = new javax.swing.JMenu();
        CreateTableMenuItem = new javax.swing.JMenuItem();
        DeleteTableMenuItem = new javax.swing.JMenuItem();
        SaveTableMenuItem = new javax.swing.JMenuItem();
        RenameTableMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanjava3.DoAnJava3App.class).getContext().getResourceMap(DoAnJava3View.class);
        mainTabP.setBackground(resourceMap.getColor("mainTabP.background")); // NOI18N
        mainTabP.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("mainTabP.border.matteColor"))); // NOI18N
        mainTabP.setName("mainTabP"); // NOI18N
        mainTabP.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainTabPMouseClicked(evt);
            }
        });
        mainTabP.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mainTabPKeyReleased(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        mainList.setBackground(resourceMap.getColor("mainList.background")); // NOI18N
        mainList.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("mainList.border.matteColor"))); // NOI18N
        mainList.setForeground(resourceMap.getColor("mainList.foreground")); // NOI18N
        mainList.setName("mainList"); // NOI18N
        mainList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainListMouseClicked(evt);
            }
        });
        mainList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mainListKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(mainList);

        mainTollBar.setRollover(true);
        mainTollBar.setName("mainTollBar"); // NOI18N

        btnAddtable.setIcon(resourceMap.getIcon("btnAddtable.icon")); // NOI18N
        btnAddtable.setText(resourceMap.getString("btnAddtable.text")); // NOI18N
        btnAddtable.setToolTipText(resourceMap.getString("btnAddtable.toolTipText")); // NOI18N
        btnAddtable.setFocusable(false);
        btnAddtable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddtable.setName("btnAddtable"); // NOI18N
        btnAddtable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddtable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddtableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnAddtable);

        btnDeletetable.setIcon(resourceMap.getIcon("btnDeletetable.icon")); // NOI18N
        btnDeletetable.setText(resourceMap.getString("btnDeletetable.text")); // NOI18N
        btnDeletetable.setToolTipText(resourceMap.getString("btnDeletetable.toolTipText")); // NOI18N
        btnDeletetable.setFocusable(false);
        btnDeletetable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDeletetable.setName("btnDeletetable"); // NOI18N
        btnDeletetable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDeletetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletetableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnDeletetable);

        btnSavetable.setIcon(resourceMap.getIcon("btnSavetable.icon")); // NOI18N
        btnSavetable.setText(resourceMap.getString("btnSavetable.text")); // NOI18N
        btnSavetable.setToolTipText(resourceMap.getString("btnSavetable.toolTipText")); // NOI18N
        btnSavetable.setFocusable(false);
        btnSavetable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSavetable.setName("btnSavetable"); // NOI18N
        btnSavetable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSavetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSavetableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnSavetable);

        jSeparator1.setName("jSeparator1"); // NOI18N
        mainTollBar.add(jSeparator1);

        btnDesignTable.setIcon(resourceMap.getIcon("btnDesignTable.icon")); // NOI18N
        btnDesignTable.setText(resourceMap.getString("btnDesignTable.text")); // NOI18N
        btnDesignTable.setToolTipText(resourceMap.getString("btnDesignTable.toolTipText")); // NOI18N
        btnDesignTable.setFocusable(false);
        btnDesignTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDesignTable.setName("btnDesignTable"); // NOI18N
        btnDesignTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDesignTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesignTableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnDesignTable);

        btnOpenTable.setIcon(resourceMap.getIcon("btnOpenTable.icon")); // NOI18N
        btnOpenTable.setText(resourceMap.getString("btnOpenTable.text")); // NOI18N
        btnOpenTable.setToolTipText(resourceMap.getString("btnOpenTable.toolTipText")); // NOI18N
        btnOpenTable.setFocusable(false);
        btnOpenTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnOpenTable.setName("btnOpenTable"); // NOI18N
        btnOpenTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnOpenTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenTableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnOpenTable);

        jSeparator4.setName("jSeparator4"); // NOI18N
        mainTollBar.add(jSeparator4);

        btnInsertrow.setIcon(resourceMap.getIcon("btnInsertrow.icon")); // NOI18N
        btnInsertrow.setText(resourceMap.getString("btnInsertrow.text")); // NOI18N
        btnInsertrow.setToolTipText(resourceMap.getString("btnInsertrow.toolTipText")); // NOI18N
        btnInsertrow.setFocusable(false);
        btnInsertrow.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnInsertrow.setName("btnInsertrow"); // NOI18N
        btnInsertrow.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnInsertrow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertrowActionPerformed(evt);
            }
        });
        mainTollBar.add(btnInsertrow);

        btnDeleterow.setIcon(resourceMap.getIcon("btnDeleterow.icon")); // NOI18N
        btnDeleterow.setText(resourceMap.getString("btnDeleterow.text")); // NOI18N
        btnDeleterow.setToolTipText(resourceMap.getString("btnDeleterow.toolTipText")); // NOI18N
        btnDeleterow.setFocusable(false);
        btnDeleterow.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDeleterow.setName("btnDeleterow"); // NOI18N
        btnDeleterow.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDeleterow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleterowActionPerformed(evt);
            }
        });
        mainTollBar.add(btnDeleterow);

        jSeparator5.setName("jSeparator5"); // NOI18N
        mainTollBar.add(jSeparator5);

        btnGofirst.setIcon(resourceMap.getIcon("btnGofirst.icon")); // NOI18N
        btnGofirst.setText(resourceMap.getString("btnGofirst.text")); // NOI18N
        btnGofirst.setToolTipText(resourceMap.getString("btnGofirst.toolTipText")); // NOI18N
        btnGofirst.setFocusable(false);
        btnGofirst.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGofirst.setName("btnGofirst"); // NOI18N
        btnGofirst.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGofirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGofirstActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGofirst);

        btnGoprevious.setIcon(resourceMap.getIcon("btnGoprevious.icon")); // NOI18N
        btnGoprevious.setText(resourceMap.getString("btnGoprevious.text")); // NOI18N
        btnGoprevious.setToolTipText(resourceMap.getString("btnGoprevious.toolTipText")); // NOI18N
        btnGoprevious.setFocusable(false);
        btnGoprevious.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGoprevious.setName("btnGoprevious"); // NOI18N
        btnGoprevious.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGoprevious.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGopreviousActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGoprevious);

        lbrow.setText(resourceMap.getString("lbrow.text")); // NOI18N
        lbrow.setName("lbrow"); // NOI18N
        mainTollBar.add(lbrow);

        btnGonext.setIcon(resourceMap.getIcon("btnGonext.icon")); // NOI18N
        btnGonext.setText(resourceMap.getString("btnGonext.text")); // NOI18N
        btnGonext.setToolTipText(resourceMap.getString("btnGonext.toolTipText")); // NOI18N
        btnGonext.setFocusable(false);
        btnGonext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGonext.setName("btnGonext"); // NOI18N
        btnGonext.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGonext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGonextActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGonext);

        btnGolast.setIcon(resourceMap.getIcon("btnGolast.icon")); // NOI18N
        btnGolast.setText(resourceMap.getString("btnGolast.text")); // NOI18N
        btnGolast.setToolTipText(resourceMap.getString("btnGolast.toolTipText")); // NOI18N
        btnGolast.setFocusable(false);
        btnGolast.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGolast.setName("btnGolast"); // NOI18N
        btnGolast.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGolast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGolastActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGolast);

        jSeparator2.setName("jSeparator2"); // NOI18N
        mainTollBar.add(jSeparator2);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanjava3.DoAnJava3App.class).getContext().getActionMap(DoAnJava3View.class, this);
        btnExit.setAction(actionMap.get("quit")); // NOI18N
        btnExit.setIcon(resourceMap.getIcon("btnExit.icon")); // NOI18N
        btnExit.setText(resourceMap.getString("btnExit.text")); // NOI18N
        btnExit.setFocusable(false);
        btnExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnExit.setName("btnExit"); // NOI18N
        btnExit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        mainTollBar.add(btnExit);

        jSeparator3.setName("jSeparator3"); // NOI18N
        mainTollBar.add(jSeparator3);

        tfSQL.setBackground(resourceMap.getColor("tfSQL.background")); // NOI18N
        tfSQL.setEditable(false);
        tfSQL.setForeground(resourceMap.getColor("tfSQL.foreground")); // NOI18N
        tfSQL.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tfSQL.setText(resourceMap.getString("tfSQL.text")); // NOI18N
        tfSQL.setName("tfSQL"); // NOI18N

        jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N
        jPanel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("jPanel1.border.matteColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        tfPassword.setEditable(false);
        tfPassword.setFont(resourceMap.getFont("tfPassword.font")); // NOI18N
        tfPassword.setForeground(resourceMap.getColor("tfPassword.foreground")); // NOI18N
        tfPassword.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("tfPassword.border.matteColor"))); // NOI18N
        tfPassword.setName("tfPassword"); // NOI18N

        tfUsername.setEditable(false);
        tfUsername.setFont(resourceMap.getFont("tfUsername.font")); // NOI18N
        tfUsername.setForeground(resourceMap.getColor("tfUsername.foreground")); // NOI18N
        tfUsername.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("tfUsername.border.matteColor"))); // NOI18N
        tfUsername.setName("tfUsername"); // NOI18N

        tfIp.setEditable(false);
        tfIp.setFont(resourceMap.getFont("tfIp.font")); // NOI18N
        tfIp.setForeground(resourceMap.getColor("tfIp.foreground")); // NOI18N
        tfIp.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("tfIp.border.matteColor"))); // NOI18N
        tfIp.setName("tfIp"); // NOI18N

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setForeground(resourceMap.getColor("jLabel4.foreground")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tfPassword)
                    .addComponent(tfUsername)
                    .addComponent(tfIp, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(tfIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainTollBar, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mainTabP, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE))
            .addComponent(tfSQL, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(mainTollBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(mainTabP, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfSQL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setIcon(resourceMap.getIcon("exitMenuItem.icon")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.setPressedIcon(resourceMap.getIcon("exitMenuItem.pressedIcon")); // NOI18N
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        TableMenu.setText(resourceMap.getString("TableMenu.text")); // NOI18N
        TableMenu.setName("TableMenu"); // NOI18N
        TableMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMenuMouseClicked(evt);
            }
        });

        CreateTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        CreateTableMenuItem.setIcon(resourceMap.getIcon("CreateTableMenuItem.icon")); // NOI18N
        CreateTableMenuItem.setText(resourceMap.getString("CreateTableMenuItem.text")); // NOI18N
        CreateTableMenuItem.setName("CreateTableMenuItem"); // NOI18N
        CreateTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(CreateTableMenuItem);

        DeleteTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
        DeleteTableMenuItem.setIcon(resourceMap.getIcon("DeleteTableMenuItem.icon")); // NOI18N
        DeleteTableMenuItem.setText(resourceMap.getString("DeleteTableMenuItem.text")); // NOI18N
        DeleteTableMenuItem.setName("DeleteTableMenuItem"); // NOI18N
        DeleteTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(DeleteTableMenuItem);

        SaveTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        SaveTableMenuItem.setIcon(resourceMap.getIcon("SaveTableMenuItem.icon")); // NOI18N
        SaveTableMenuItem.setText(resourceMap.getString("SaveTableMenuItem.text")); // NOI18N
        SaveTableMenuItem.setName("SaveTableMenuItem"); // NOI18N
        SaveTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(SaveTableMenuItem);

        RenameTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
        RenameTableMenuItem.setIcon(resourceMap.getIcon("RenameTableMenuItem.icon")); // NOI18N
        RenameTableMenuItem.setText(resourceMap.getString("RenameTableMenuItem.text")); // NOI18N
        RenameTableMenuItem.setName("RenameTableMenuItem"); // NOI18N
        RenameTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenameTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(RenameTableMenuItem);

        menuBar.add(TableMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setIcon(resourceMap.getIcon("aboutMenuItem.icon")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 593, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void CreateTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateTableMenuItemActionPerformed
// TODO add your handling code here:
    name = JOptionPane.showInputDialog(null, "Enter Table's Name", "New Table", 1);

    if (name == null)
        return;
    else if ("".equals(name))
        JOptionPane.showMessageDialog(null, "Table Name can't null\r\nCreate Table faill.", "Error", 0);
    else
    {
        //tao 1 bang moi o dang thiet ke
        final JTable tbdesign = createTableDesign();
        tbdesign.setName(name + "Design");
        //bang tbdesign bat su kien click vao dong cuoi cung thi phat sinh them dong moi
        newRowListener(tbdesign);
        //xu ly su kien thay doi du lieu o o dau tien cua dong cua bang desing(gia tri la Column Name)
        changCellDataListtener(tbdesign);
        //bat su kien de xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
        tbdesign.addKeyListener(new KeyListener()
        {

            public void keyReleased(KeyEvent e)
            {
                //xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
                verifyRowPosition(lstTBDes);
            }

            public void keyTyped(KeyEvent e)
            {
            }

            public void keyPressed(KeyEvent e)
            {
            }
        });
        //them mau nen cho bang tbdesign
        tbdesign.getTableHeader().setForeground(Color.magenta);
        //them bang vua tao vao danh sach cac bang thiet ke
        lstTBDes.add(tbdesign);
        //tao bang open
        String rowdata[][] =
        {
            {
                null
            }
        };
        String colName[] =
        {
            "ID"
        };
        DefaultTableModel defmodel = new DefaultTableModel(rowdata, colName);
        JTable tbopen = new JTable(defmodel);
        //cat bo phan ten "Design" va gan vao "Open"
        String strname = tbdesign.getName();
        strname = strname.substring(0, strname.length() - 6);
        strname += "Open";
        tbopen.setName(strname);
        //them mau nen cho bang tbopen
        tbopen.getTableHeader().setForeground(Color.magenta);
        //bang tbdesign bat su kien click vao dong cuoi cung thi phat sinh them dong moi
        newRowListener(tbopen);
        //them bang vua tao vao danh sach cac bang nhap lieu
        lstTBOpe.add(tbopen);
        //bat su kien de xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
        tbopen.addKeyListener(new KeyListener()
        {

            public void keyReleased(KeyEvent e)
            {
                //xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
                verifyRowPosition(lstTBDes);
            }

            public void keyTyped(KeyEvent e)
            {
            }

            public void keyPressed(KeyEvent e)
            {
            }
        });
        //them item moi cho mainList
        modelList.add(modelList.getSize(), name);
        mainList.setModel(modelList);
        //them tab moi cho tabpanel
        JScrollPane scrollpane = new JScrollPane();
        scrollpane.setName(name + "ScrollPane");
        scrollpane.setViewportView(tbdesign);
        lstCrollP.add(scrollpane);
        //lay hinh tu resources de add vao tabbedpane
        ImageIcon imageicon = getImageIconFromFile(pathImageIcon);
        //add bang moi, hinh vao tabbedpane
        mainTabP.addTab(name, imageicon, scrollpane);
        //cho con tro chuot chon bang vua tao
        mainList.setSelectedIndex(modelList.size() - 1);
        mainTabP.setSelectedIndex(mainTabP.getTabCount() - 1);
        //them tinh trang da luu (doi voi bang vua tao) vao danh sach tinh trang (save/don't save)
        lstIsSaved.add(true);
    }

}//GEN-LAST:event_CreateTableMenuItemActionPerformed

private void DeleteTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteTableMenuItemActionPerformed
// TODO add your handling code here:
    //lay ve tat ca vi tri cac item duoc chon
    //JOptionPane.showMessageDialog(null, "Are you sure delete " + mainList., name, busyIconIndex, idleIcon);
    int[] Selecteds = mainList.getSelectedIndices();
    if (Selecteds.length > 0)
    {
        int result = JOptionPane.showConfirmDialog(null, "Are you sure delete selected table(s)?", "Delete table(s)", 0, 3);
        if (result == JOptionPane.YES_OPTION)
        {
            for (int i = Selecteds.length; i > 0; i--)
            {
                //xoa cac item duoc chon trong mainList
                modelList.remove(Selecteds[i - 1]);
                //xoa cac tabPane tuong ung
                mainTabP.remove(Selecteds[i - 1]);
                //xoa bang khoi danh sach cac bang thiet ke
                lstTBDes.remove(Selecteds[i - 1]);
                //xoa cac tinh trang tuong ung cua bang vua xoa
                lstIsSaved.remove(Selecteds[i - 1]);
            }
        }
        //cho con tro chon bang dau tien trong main list, khi con du lieu
        if (mainList.getModel().getSize() != 0)
        {
            mainList.setSelectedIndex(0);
            mainTabP.setSelectedIndex(0);
            verifyRowPosition(lstTBOpe);
            verifyRowPosition(lstTBDes);
        }
    }
}//GEN-LAST:event_DeleteTableMenuItemActionPerformed

private void mainListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainListMouseClicked
// TODO add your handling code here:
    mainListEventFunction();
}//GEN-LAST:event_mainListMouseClicked

private void mainTabPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainTabPMouseClicked
// TODO add your handling code here:
    mainTabPEventFunction();
}//GEN-LAST:event_mainTabPMouseClicked

private void SaveTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveTableMenuItemActionPerformed
// TODO add your handling code here:
        //danh dau bang dang mo tren tabpanel da duoc luu (true)
        lstIsSaved.set(mainTabP.getSelectedIndex(), Boolean.TRUE);
        updateTableOpening();
    }

    private void openTableOpen()
    {
        // TODO add your handling code here:
        //lay ve chi so cua bang dang chon
        int indextablesel = mainList.getSelectedIndex();
        //anh xa cau truc cua design qua bang open
        JTable tbopen = convertTableDesToOpe(lstTBDes.get(indextablesel));
        //cho tbopen lang nghe su kien khi click vao dong cua no
        newRowListener(tbopen);
        //cho moi table lang nghe su kien khi nhan phim KeyUp - KeyDown
        tbopen.addKeyListener(new KeyListener()
        {

            //bat su kien nha phim ra
            public void keyReleased(KeyEvent e)
            {
                verifyRowPosition(lstTBOpe);
            }

            public void keyTyped(KeyEvent e)
            {
            }

            public void keyPressed(KeyEvent e)
            {
            }
        });
        lstTBOpe.remove(indextablesel);
        lstTBOpe.add(indextablesel, tbopen);
        //cho scrollpanel hien thi bang open tuong ung
        lstCrollP.get(indextablesel).setViewportView(lstTBOpe.get(indextablesel));
        //xac dinh vi tri cung dong dang chon/tong so dong cua bang hien thoi
        verifyRowPosition(lstTBOpe);
    }

    private void updateTableOpening()
    {
        //cap nhat lai table design dang duoc chon o tab panel
        JScrollPane crollpane = (JScrollPane) mainTabP.getSelectedComponent();
        JTable table = (JTable) crollpane.getViewport().getView();
        int idex = mainTabP.getSelectedIndex();
        String strname = lstTBDes.get(idex).getName().toString();
        table.setName(strname);
}//GEN-LAST:event_SaveTableMenuItemActionPerformed

private void btnAddtableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddtableActionPerformed
// TODO add your handling code here:
    CreateTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnAddtableActionPerformed

private void btnDeletetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletetableActionPerformed
// TODO add your handling code here:
    DeleteTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnDeletetableActionPerformed

private void btnSavetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSavetableActionPerformed
// TODO add your handling code here:
    SaveTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnSavetableActionPerformed

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
// TODO add your handling code here:
    exitProgrameFunction();
}//GEN-LAST:event_btnExitActionPerformed

private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
    exitProgrameFunction();
}//GEN-LAST:event_exitMenuItemActionPerformed

private void RenameTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenameTableMenuItemActionPerformed
// TODO add your handling code here:
    //hien thi hop thoai yeu cau nhap ten moi cho bang da chon
    String newName = JOptionPane.showInputDialog(null, "Enter new name for table: ", "Rename Table", 1);

    if (newName == null)
        return;
    else if ("".equals(newName))
        JOptionPane.showMessageDialog(null, "Table Name can't null\r\nRename Table faill.", "Error", 0);
    else
    {
        //lay chi so item dang duoc chon trong mainList
        int indexSel = mainList.getSelectedIndex();
        //doi ten moi cho item va tab dang chon
        modelList.setElementAt(newName, indexSel);
        mainTabP.setTitleAt(indexSel, newName);
        //doi ten bang trong danh sach bang design
        lstTBDes.get(indexSel).setName(newName + "Design");
    }
}//GEN-LAST:event_RenameTableMenuItemActionPerformed

private void TableMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMenuMouseClicked
// TODO add your handling code here:
    //lay ve so bang dang co
    int nTable = mainList.getModel().getSize();
    System.out.println(nTable);
    //neu ko co bang nao het thi an 1 so chuc nang
    if (nTable == 0)
    {
        DeleteTableMenuItem.setEnabled(false);
        SaveTableMenuItem.setEnabled(false);
        RenameTableMenuItem.setEnabled(false);
    }
    else
    {
        DeleteTableMenuItem.setEnabled(true);
        SaveTableMenuItem.setEnabled(true);
        RenameTableMenuItem.setEnabled(true);
    }
}//GEN-LAST:event_TableMenuMouseClicked

private void btnGolastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGolastActionPerformed
// TODO add your handling code here:
    //lay ve thu tu cua bang dang duoc chon
    int idextablesel = mainTabP.getSelectedIndex();
    //lay ve tong so dong cua bang dang chon
    int totalrow = lstTBDes.get(idextablesel).getRowCount();
    //cho con tro chon dong cuoi cung cua bang
    lstTBDes.get(idextablesel).setRowSelectionInterval(totalrow - 1, totalrow - 1);
    //cap nhat lai vi tri dong dang chon/tong so dong cua bang
    lbrow.setText(totalrow + "/" + totalrow);
    //cho 2 button goNext va goLast an di
    btnGonext.setEnabled(false);
    btnGolast.setEnabled(false);
    //cho 2 button goPrevious va goFirst hien len
    btnGoprevious.setEnabled(true);
    btnGofirst.setEnabled(true);
}//GEN-LAST:event_btnGolastActionPerformed

private void btnGonextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGonextActionPerformed
// TODO add your handling code here:
    goNextFunction();
}//GEN-LAST:event_btnGonextActionPerformed

private void btnGofirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGofirstActionPerformed
// TODO add your handling code here:
    //lay ve thu tu cua bang dang duoc chon
    int idextablesel = mainTabP.getSelectedIndex();
    //lay ve tong so dong cua bang dang chon
    int totalrow = lstTBDes.get(idextablesel).getRowCount();
    //cho con tro chon dong cuoi cung cua bang
    lstTBDes.get(idextablesel).setRowSelectionInterval(0, 0);
    //cap nhat lai vi tri dong dang chon/tong so dong cua bang
    lbrow.setText(1 + "/" + totalrow);
    //cho 2 button goNext va goLast hien len
    btnGonext.setEnabled(true);
    btnGolast.setEnabled(true);
    //cho 2 button goPrevious va goFirst an di
    btnGoprevious.setEnabled(false);
    btnGofirst.setEnabled(false);
}//GEN-LAST:event_btnGofirstActionPerformed

private void btnGopreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGopreviousActionPerformed
// TODO add your handling code here:
    goPreviousFunction();
}//GEN-LAST:event_btnGopreviousActionPerformed

private void mainListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mainListKeyReleased
// TODO add your handling code here:
    mainListEventFunction();
}//GEN-LAST:event_mainListKeyReleased

private void mainTabPKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mainTabPKeyReleased
// TODO add your handling code here:
    mainTabPEventFunction();
}//GEN-LAST:event_mainTabPKeyReleased

private void btnDesignTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDesignTableActionPerformed
// TODO add your handling code here:
    //lay ve chi so cua bang dang chon
    int indextablesel = mainList.getSelectedIndex();
    //neu bang dang mo la bang open moi mo sang bang design
    if ((JTable) (lstCrollP.get(indextablesel).getViewport().getView()) == lstTBOpe.get(indextablesel))
    {
        //cho scrollpanel hien thi bang design tuong ung
        lstCrollP.get(indextablesel).setViewportView(lstTBDes.get(indextablesel));
        //xac dinh vi tri cung dong dang chon/tong so dong cua bang hien thoi
        verifyRowPosition(lstTBDes);
    }
}//GEN-LAST:event_btnDesignTableActionPerformed

private void btnOpenTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenTableActionPerformed
    //mo bang Open tuong ung tren tabbedpanel
//    openTableOpen();
    //lay chi so cua bang dang duoc chon
    int indexsel = mainList.getSelectedIndex();
    //neu bang dang mo la bang design moi mo sang bang open
    if ((JTable) (lstCrollP.get(indexsel).getViewport().getView()) == lstTBDes.get(indexsel))
    {
        //chuan hoa 2 bang design va open tuong ung
        formateTableCorrect(lstTBDes.get(indexsel), lstTBOpe.get(indexsel));
        //mo bang open len
        lstCrollP.get(indexsel).setViewportView(lstTBOpe.get(indexsel));
        //xac dinh vi tri cung dong dang chon/tong so dong cua bang hien thoi
        verifyRowPosition(lstTBOpe);
    }
}//GEN-LAST:event_btnOpenTableActionPerformed

private void btnDeleterowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleterowActionPerformed
// TODO add your handling code here:
    //lay chi so bang dang duoc chon
    int indexsel = mainList.getSelectedIndex();
    //neu bang chi con 1 dong duy nhat thi khong xoa
    if (((JTable) lstCrollP.get(indexsel).getViewport().getView()).getRowCount() == 1)
    {
        JOptionPane.showMessageDialog(null, "You can't delete this row!", "Error delete row!", 0);
    }
    else
    {
        DefaultTableModel defmodel = new DefaultTableModel();
        //lay ve model cua bang dang duoc mo trong tabbedpanel
        defmodel = (DefaultTableModel) ((JTable) lstCrollP.get(indexsel).getViewport().getView()).getModel();
        //xoa di dong dang duoc chon cua bang do
        int indexrowsel = ((JTable) lstCrollP.get(indexsel).getViewport().getView()).getSelectedRow();
        defmodel.removeRow(indexrowsel);
        //chon con tro chon o dong dau tien cua bang
        ((JTable) lstCrollP.get(indexsel).getViewport().getView()).setRowSelectionInterval(0, 0);
        //neu nhu bang dang mo la bang design thi can xoa cot o vi tri tuong ung o bang open
        if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
        {
            //xoa 1 cot o vi tri tuong ung trong bang open
            deleteColumnTableOpen(indexrowsel);
        }
    }
}//GEN-LAST:event_btnDeleterowActionPerformed

private void btnInsertrowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertrowActionPerformed
// TODO add your handling code here:
    //lay chi so bang dang duoc chon
    int indexsel = mainList.getSelectedIndex();
    DefaultTableModel defmodel = new DefaultTableModel();
    //lay ve model cua bang dang duoc mo trong tabbedpanel
    defmodel = (DefaultTableModel) ((JTable) lstCrollP.get(indexsel).getViewport().getView()).getModel();
    //them vao 1 dong TREN dong dang duoc chon cua bang do
    int indexrowsel = ((JTable) lstCrollP.get(indexsel).getViewport().getView()).getSelectedRow();
    defmodel.insertRow(indexrowsel, new Vector());
    //neu nhu bang dang mo la bang design thi can them cot o vi tri tuong ung o bang open
    if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
    {
        //them 1 cot o vi tri tuong ung trong bang open
        addColumnToTableOpen(indexrowsel);
    }
}//GEN-LAST:event_btnInsertrowActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem CreateTableMenuItem;
    private javax.swing.JMenuItem DeleteTableMenuItem;
    private javax.swing.JMenuItem RenameTableMenuItem;
    private javax.swing.JMenuItem SaveTableMenuItem;
    private javax.swing.JMenu TableMenu;
    private javax.swing.JButton btnAddtable;
    private javax.swing.JButton btnDeleterow;
    private javax.swing.JButton btnDeletetable;
    private javax.swing.JButton btnDesignTable;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnGofirst;
    private javax.swing.JButton btnGolast;
    private javax.swing.JButton btnGonext;
    private javax.swing.JButton btnGoprevious;
    private javax.swing.JButton btnInsertrow;
    private javax.swing.JButton btnOpenTable;
    private javax.swing.JButton btnSavetable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar.Separator jSeparator5;
    private javax.swing.JLabel lbrow;
    private javax.swing.JList mainList;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTabbedPane mainTabP;
    private javax.swing.JToolBar mainTollBar;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    javax.swing.JTextField tfIp;
    private javax.swing.JTextField tfPassword;
    private static javax.swing.JTextField tfSQL;
    javax.swing.JTextField tfUsername;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    private void writeListTableToFile(ArrayList<JTable> lsttable, String pathfile)
    {
        clsTable clstable = new clsTable();
        clstable.writeListTableToFile(lsttable, pathfile);
    }

    private ArrayList<JTable> getListTableFromFile(String pathfile) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        clsTable clstable = new clsTable();
        return clstable.getListTableFromFile(pathfile);
    }

    private void viewListTable(ArrayList<JTable> lsttbdes)
    {

        String[] strName = new String[lsttbdes.size()];
        String strname = "";
        int nSize = lsttbdes.size();
        for (int i = 0; i < nSize; i++)
        {
            //tao mau nen cho tieu de cot
            lstTBDes.get(i).getTableHeader().setForeground(Color.magenta);
            lstTBOpe.get(i).getTableHeader().setForeground(Color.magenta);
            strName[i] = lsttbdes.get(i).getName();
            strname = strName[i].substring(0, strName[i].length() - 6);
            modelList.add(modelList.getSize(), strname);
            mainList.setModel(modelList);
            //them tab moi cho tabpanel
            JScrollPane scrollpane = new JScrollPane();
            scrollpane.setName(strname + "ScrollPane");
            scrollpane.setViewportView(lsttbdes.get(i));
            lstCrollP.add(scrollpane);
            //lay ImageIcon tu duong dan
            ImageIcon imageicon = getImageIconFromFile(pathImageIcon);
            //them bang vao tabbedpane, vao add ImageIcon vao tabbedpane
            mainTabP.addTab(strname, imageicon, scrollpane);
            //them tinh trang da luu (doi voi bang vua tao) vao danh sach tinh trang (save/don't save)
            lstIsSaved.add(true);
        }
        //cho con tro chuot chon bang vua tao
        mainList.setSelectedIndex(nSize - 1);
        //xac dinh vi tri cua dong dang duoc chon/trong so dong cua bang
        verifyRowPosition(lsttbdes);
    }

    private void verifyRowPosition(ArrayList<JTable> lsttable)
    {
        //lay tong so dong cua bang dang duoc chon
        int totalrow = lsttable.get(mainList.getSelectedIndex()).getRowCount();
        //lay vi tri dong dang duoc cho trong bang
        int indexrowsel = lsttable.get(mainList.getSelectedIndex()).getSelectedRow() + 1;
        lbrow.setText(indexrowsel + "/" + totalrow);
        //neu dang chon o dong dau tien
        if (indexrowsel == 1)
        {
            btnGofirst.setEnabled(false);
            btnGoprevious.setEnabled(false);
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
        }
        else if (indexrowsel == totalrow)
        {
            btnGonext.setEnabled(false);
            btnGolast.setEnabled(false);
            btnGofirst.setEnabled(true);
            btnGoprevious.setEnabled(true);
        }
        else
        {
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
            btnGofirst.setEnabled(true);
            btnGoprevious.setEnabled(true);
        }
        //neu dang chon o dong cuoi cung
    }

    private void newRowListener(final JTable table)
    {
        final DefaultTableModel model = (DefaultTableModel) table.getModel();
        //table se lang nghe su kien click vao dong cuoi cung se them dong moi
        table.addMouseListener(new java.awt.event.MouseAdapter()
        {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                if (table.getSelectedRow() == table.getRowCount() - 1)
                {
                    //them vao dong cuoi cung
//                    model.addRow(new Object[2]);
                    model.addRow(new Vector());
                    //lay chi so cua bang dang chon
                    int indexsel = mainList.getSelectedIndex();
                    //lay chi so cua dong cuoi cung cua bang
                    int indexrowsel = ((JTable) lstCrollP.get(indexsel).getViewport().getView()).getRowCount() - 1;
                    //neu nhu bang dang mo la bang design thi can them cot o vi tri tuong ung o bang open
                    if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
                    {
                        //them 1 cot o vi tri tuong ung trong bang open
                        addColumnToTableOpen(indexrowsel);
                    }
                }
                //xac dinh vi tri dong duoc chon/trong so dong cua bang
                verifyRowPositionCorrect();
            }
        });
    }

    private void mainListEventFunction()
    {
        //neu co chon 1 item trem mainList
        if (mainList.getSelectedIndex() != -1)
        {
            //kiem tra xem bang truoc do da luu hay chua
            if (mainTabP.getSelectedIndex() != mainList.getSelectedIndex())
            {
                //neu nhu co thao tac lam thay doi gia tri cua bang ma chua luu lai
                if (lstIsSaved.get(mainTabP.getSelectedIndex()) == false)
                {
                    int result = JOptionPane.showConfirmDialog(null, "Do you save " + name + "'s Table?", "Save Table?", 0, 3);
                    if (result == JOptionPane.YES_OPTION)
                    {
                        //cap nhat lai dua lieu, goi su kien khi nhan nut save table
                        SaveTableMenuItemActionPerformed(null);
                    }
                    else
                    {
                        lstIsSaved.set(mainTabP.getSelectedIndex(), Boolean.TRUE);
//                    lstCrollP.get(mainTabP.getSelectedIndex()).setViewportView(lstTBDes.get(mainTabP.getSelectedIndex()));
//                    JScrollPane crollpane = (JScrollPane)mainTabP.getComponent(mainTabP.getSelectedIndex());
//                    crollpane.setViewportView(lstTBDes.get(mainTabP.getSelectedIndex()-1));
                    }
                }
            }
            int indexsel = mainList.getSelectedIndex();
            //cho tabPanel tuong ung cung chon theo luon
            mainTabP.setSelectedIndex(indexsel);
            //xac dinh vi tri cua dong dang chon/tren tong so dong cua bang
            if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
            {
                verifyRowPosition(lstTBDes);

            }
            else
            {
                verifyRowPosition(lstTBOpe);
            }
        }
    }

    private void mainTabPEventFunction()
    {
        if (mainTabP.getSelectedIndex() != -1)
        {
            mainList.setSelectedIndex(mainTabP.getSelectedIndex());
            //xac dinh vi tri cua dong dang chon/tren tong so dong cua bang
            verifyRowPositionCorrect();
        }
    }

    private void goNextFunction()
    {
        //lay ve thu tu cua bang dang duoc chon
        int idextablesel = mainTabP.getSelectedIndex();
        //lay ve tong so dong cua bang dang chon
        int totalrow = lstTBDes.get(idextablesel).getRowCount();
        //lay ve vi tri cua dong dang duoc chon
        int idexrowsel = lstTBDes.get(idextablesel).getSelectedRow();
        //neu chua chon o dong cuoi dung
        if (idexrowsel != totalrow - 1)
        {
            idexrowsel++;
            lstTBDes.get(idextablesel).setRowSelectionInterval(idexrowsel, idexrowsel);
            //cap nhat lai vi tri dong dang chon/tong so dong cua bang
            lbrow.setText(idexrowsel + 1 + "/" + totalrow);
            //cho 2 button goPrevious va goFirst hien len
            btnGoprevious.setEnabled(true);
            btnGofirst.setEnabled(true);
            //neu da den dong cuoi cung, cho 2 button goNext va goLast an di
            if (idexrowsel == totalrow - 1)
            {
                btnGonext.setEnabled(false);
                btnGolast.setEnabled(false);
            }
        }
    }

    private void goPreviousFunction()
    {
        //lay ve thu tu cua bang dang duoc chon
        int idextablesel = mainTabP.getSelectedIndex();
        //lay ve tong so dong cua bang dang chon
        int totalrow = lstTBDes.get(idextablesel).getRowCount();
        //lay ve vi tri cua dong dang duoc chon
        int idexrowsel = lstTBDes.get(idextablesel).getSelectedRow();
        //neu chua chon o dong dau tien
        if (idexrowsel != 0)
        {
            idexrowsel--;
            lstTBDes.get(idextablesel).setRowSelectionInterval(idexrowsel, idexrowsel);
            //cap nhat lai vi tri dong dang chon/tong so dong cua bang
            lbrow.setText(idexrowsel + 1 + "/" + totalrow);
            //cho 2 button goNext va goLast hien len
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
            //neu da chon den dong dau tien, cho 2 button goPrevious va goFirst an di
            if (idexrowsel == 0)
            {
                btnGoprevious.setEnabled(false);
                btnGofirst.setEnabled(false);
            }
        }
    }

    private ImageIcon getImageIconFromFile(String pathimageicon)
    {
        ImageIcon imageicon = null;
        java.net.URL imgURL = getClass().getResource(pathimageicon);
        if (imgURL != null)
        {
            imageicon = new ImageIcon(this.getClass().getResource(pathimageicon));
        }
        else
        {
            System.err.println("Couldn't find file: " + pathimageicon);
        }
        return imageicon;
    }

    private ArrayList<JTable> getListTableOpen(ArrayList<JTable> lsttbdes)
    {
        ArrayList<JTable> lsttbope = new ArrayList<JTable>();
        for (int i = 0; i < lsttbdes.size(); i++)
        {
            JTable tbopen = convertTableDesToOpe(lsttbdes.get(i));
            //them bang open vao danh sach
            lsttbope.add(tbopen);
        }
        return lsttbope;
    }

    private JTable convertTableDesToOpe(JTable tbdesign)
    {
        //chuan hoa bang tbdesign - bo cac dong trong o cot Name Column
        formateTable(tbdesign);
        //dem so dong co du lieu (mac dinh la bo dong cuoi cung)
        int iSize = tbdesign.getRowCount();
        String lstColName[] = new String[iSize];
        String lstColType[] = new String[iSize];
        String data[] = new String[iSize];

        for (int i = 0; i < iSize; i++)
        {
            lstColName[i] = (String) tbdesign.getValueAt(i, 0);
            lstColType[i] = (String) tbdesign.getValueAt(i, 1);
            data[i] = "";
        }
        //tao du lieu cho 1 dong
        String rowdata[][] =
        {
            data
        };
        //tao bang open
        DefaultTableModel defmodel = new DefaultTableModel(rowdata, lstColName);
        JTable tbopen = new JTable(defmodel);
        //cat bo phan ten "Design" va gan vao "Open"
        String strname = tbdesign.getName();
        strname = strname.substring(0, strname.length() - 6);
        strname += "Open";
        tbopen.setName(strname);
        return tbopen;
    }

    private void saveDatabaseToFile(clsDatabase mydatabase, String pathdata)
    {
        try
        {
            FileOutputStream fos = new FileOutputStream(pathdata);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(mydatabase);
            System.out.println("Da ghi du lieu xuong file!");
            oos.close();
        } catch (NotSerializableException nse)
        {
            System.out.println(nse.getMessage());
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    private clsDatabase loadDatabaseFromFile(String pathdata) throws IOException, ClassNotFoundException
    {
        clsDatabase database = new clsDatabase();
        try
        {
            FileInputStream fis = new FileInputStream(pathdata);
            ObjectInputStream ois = new ObjectInputStream(fis);
            database = (clsDatabase) ois.readObject();
            ois.close();
        } catch (NotSerializableException nse)
        {
            System.out.println(nse.getMessage());
        } catch (WriteAbortedException wae)
        {
            System.out.println(wae.getMessage());
        }
        return database;
    }

    private void formateTable(JTable tbdesign)
    {
        DefaultTableModel defmodel = new DefaultTableModel();
        defmodel = (DefaultTableModel) tbdesign.getModel();
        for (int i = tbdesign.getRowCount() - 1; i >= 0; i--)
        {
            //xoa dong khong co Table Name cua bang tbdesign
            if (tbdesign.getValueAt(i, 0) == null)
            {
                defmodel.removeRow(i);
            }
        }
        for (int i = tbdesign.getRowCount() - 1; i >= 0; i--)
        {
            //neu bang tbdesign co ten Table Name ma khong co Data Type thi se gan Data Type = String
            if (tbdesign.getValueAt(i, 0) != null && tbdesign.getValueAt(i, 1) == null)
            {
                tbdesign.setValueAt("String", i, 1);
            }
        }
    }

    private void verifyRowPositionCorrect()
    {
        //xac dinh vi tri cua dong dang chon/tren tong so dong cua bang
        int indexsel = mainTabP.getSelectedIndex();
        if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBOpe.get(indexsel))
            verifyRowPosition(lstTBOpe);
        else
            verifyRowPosition(lstTBDes);
    }

    private void addColumnToTableOpen(int indexcol)
    {
        //lay ve chi so cua bang dang duoc chon
        int indextable = mainList.getSelectedIndex();
        //them cot moi vao bang open tuong ung o vi tri indexcol
        lstTBOpe.get(indextable).setAutoCreateColumnsFromModel(false);
        DefaultTableModel defmodel = new DefaultTableModel();
        defmodel = (DefaultTableModel) lstTBOpe.get(indextable).getModel();
        TableColumn tablecol = new TableColumn(defmodel.getColumnCount());
        tablecol.setHeaderValue("");
        lstTBOpe.get(indextable).addColumn(tablecol);
        defmodel.addColumn("".toString(), new Vector());
        lstTBOpe.get(indextable).moveColumn(lstTBOpe.get(indextable).getColumnCount() - 1, indexcol);
    }

    private void formateTableCorrect(JTable tbdesign, JTable tbopen)
    {
        DefaultTableModel modeldes = new DefaultTableModel();
        modeldes = (DefaultTableModel) tbdesign.getModel();
        for (int i = tbdesign.getRowCount() - 1; i >= 0; i--)
        {
            //xoa dong khong co Table Name cua bang tbdesign
            if (tbdesign.getValueAt(i, 0) == null || tbdesign.getValueAt(i, 0) == "")
            {
                modeldes.removeRow(i);
                removeColumn(tbopen, i);
            }
        }
        for (int i = tbdesign.getRowCount() - 1; i >= 0; i--)
        {
            //neu bang tbdesign co ten Table Name ma khong co Data Type thi se gan Data Type = String
            if (tbdesign.getValueAt(i, 0) != null && tbdesign.getValueAt(i, 1) == null)
            {
                tbdesign.setValueAt("String", i, 1);
            }
        }
    }

    private void removeColumn(JTable table, int index)
    {
        TableColumn tablecol = table.getColumnModel().getColumn(index);
        table.removeColumn(tablecol);
    }

    private void changCellDataListtener(final JTable table)
    {
        table.getDefaultEditor(String.class).addCellEditorListener(new CellEditorListener()
        {

            public void editingStopped(ChangeEvent e)
            {
                System.out.println("The user stopped editing successfully.");
                //lay ve chi so cua dong dang duoc chon trong bang table
                int indexsel = table.getSelectedRow();
                //lay ve gia tri cua o thay doi
                String cellData = (String) table.getValueAt(indexsel, 0);
                //lay ve chi so cua bang dang duoc chon
                int indextablesel = mainList.getSelectedIndex();
                System.out.println(cellData);
                //anh xa column name trong bang design voi header column tuong ung trong bang open
                lstTBOpe.get(indextablesel).getColumnModel().getColumn(indexsel).setHeaderValue(cellData);
            }

            public void editingCanceled(ChangeEvent e)
            {
                System.out.println("The user canceled editing.");
            }
        });

//        table.getModel().addTableModelListener(new TableModelListener()
//        {
//
//            public void tableChanged(TableModelEvent e)
//            {
//                //lay ve chi so cua dong dang duoc chon trong bang table
//                int indexsel = table.getSelectedRow();
//                //lay ve gia tri cua o thay doi
//                String cellData = (String) table.getValueAt(indexsel, 0);
//                //lay ve chi so cua bang dang duoc chon
//                int indextablesel = mainList.getSelectedIndex();
//                System.out.println(cellData);
//                //anh xa column name trong bang design voi header column tuong ung trong bang open
//                lstTBOpe.get(indextablesel).getColumnModel().getColumn(indexsel).setHeaderValue(cellData);
//            }
//        });
    }

    private void deleteColumnTableOpen(int indexcol)
    {
        //lay ve chi so cua bang dang duoc chon
        int indextable = mainList.getSelectedIndex();
        //xoa cot o bang open tuong ung o vi tri indexcol
        lstTBOpe.get(indextable).removeColumn(lstTBOpe.get(indextable).getColumnModel().getColumn(indexcol));
    }

    private void initInputServer()
    {
        InetAddress thisIp;
        try
        {
            thisIp = InetAddress.getLocalHost();
            strIP = thisIp.getHostAddress();
            strUserName = thisIp.getHostName();
            strPass = thisIp.getAddress().toString();
            strPass = strPass.substring(4);

            //gan nhung thong tin tren cho cac textfield
            tfIp.setText(strIP);
            tfUsername.setText(strUserName);
            tfPassword.setText(strPass);
        } catch (UnknownHostException ex)
        {
            Logger.getLogger(DoAnJava3View.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

class clsTable
{

    void writeListTableToFile(ArrayList<JTable> lsttable, String pathfile)
    {
        int i = 0;
        try
        {
            FileOutputStream fos = new FileOutputStream(pathfile);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            for (i = 0; i < lsttable.size(); i++)
            {
                System.out.println(lsttable.get(i).getName());
                oos.writeObject(lsttable.get(i));
                oos.flush();
            }
            oos.close();
            fos.close();
            fos.close();
        } catch (Exception e)
        {
            System.out.println(e.getMessage().toString());
        }
        System.out.println(lsttable.size());
    }

    ArrayList<JTable> getListTableFromFile(String pathfile) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        ArrayList<JTable> lsttable = new ArrayList<JTable>();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try
        {
            fis = new FileInputStream(pathfile);
            ois = new ObjectInputStream(fis);
            Object obj = null;
            while ((obj = ois.readObject()) != null)
            {
                if (obj instanceof JTable)
                {
                    final JTable table = (JTable) obj;
                    //them table vao danh sach
                    lsttable.add(table);
                }
            }
        } catch (EOFException e)
        {
            System.out.println("End of File");
        } finally
        {
            try
            {
                if (fis != null)
                {
                    fis.close();
                }
            } catch (IOException ex)
            {
            }
        }
        return lsttable;
    }

    public void newRowListener(final JTable table)
    {
        final DefaultTableModel model = (DefaultTableModel) table.getModel();
        //table se lang nghe su kien click vao dong cuoi cung se them dong moi
        table.addMouseListener(new java.awt.event.MouseAdapter()
        {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                if (table.getSelectedRow() == table.getRowCount() - 1)
                {
                    model.addRow(new Object[2]);
                }
            }
        });
    }

    public void propertyChange(PropertyChangeEvent evt)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

class clsDatabase implements java.io.Serializable
{
    //list chua danh sach cac bang o che do design

    private ArrayList<JTable> lstTBDes = new ArrayList<JTable>();
    //list chua danh sach cac bang o che do open
    private ArrayList<JTable> lstTBOpe = new ArrayList<JTable>();

    public clsDatabase()
    {
        lstTBDes = null;
        lstTBOpe = null;
    }

    /**
     * @return the lstTBDes
     */
    public ArrayList<JTable> getLstTBDes()
    {
        return lstTBDes;
    }

    /**
     * @param lstTBDes the lstTBDes to set
     */
    public void setLstTBDes(ArrayList<JTable> lstTBDes)
    {
        this.lstTBDes = lstTBDes;
    }

    /**
     * @return the lstTBOpe
     */
    public ArrayList<JTable> getLstTBOpe()
    {
        return lstTBOpe;
    }

    /**
     * @param lstTBOpe the lstTBOpe to set
     */
    public void setLstTBOpe(ArrayList<JTable> lstTBOpe)
    {
        this.lstTBOpe = lstTBOpe;
    }
}
